import React from 'react';
import './index.less';
import {nanoid} from 'nanoid';

class ToDoHeader extends React.Component {

  state = {
    itemName:'',
    textLimit:15
  }
  saveItemName = event =>{
    let inputValue = event.target.value
    if(this.state.textLimit < inputValue.length){
      let maxStr = event.target.value.substring(0,this.state.textLimit);
      this.setState({itemName:maxStr});
    }else{
      this.setState({itemName:event.target.value});
    }
  }

  createToDoItem = event =>{
    const {itemName} = this.state;
    //check
    if(itemName === ''){
      alert('任务名称不能为空！');
      this.focus();
      return;
    }
    if(this.props.checkItemNameSame(itemName)){
      alert('任务名称不能重复！');
      this.focus();
      return;
    }

    //用 nanoid 生成唯一键 yarn add nanoid
		const itemObj = {id:nanoid(),itemName:itemName,finalInd:false};
		//将todoObj传递给App
		this.props.addItem(itemObj);
    //添加后清除文本
    this.setState({itemName:''});
  }

  focus = () => {
    this.addInput.focus();
  }

  render() {
    return (
        <div className='content-top'>
          <div className='input-area'>
            <p className="top-item app-title">任务名称</p>
            <input value={this.state.itemName} ref={input => this.addInput = input } onChange={this.saveItemName} type="text" className="todo-input top-item" placeholder="添加ToDo"/>
          </div>
          <button onClick={this.createToDoItem} className="btn-add top-item">添加任务</button>
        </div>
    );
  }
}

export default ToDoHeader;
